package cl.kaisanetwork.kaisaportal.domain.dao.impl;

import java.util.List;

import javax.jdo.annotations.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

import org.springframework.orm.jpa.JpaTemplate;

import cl.kaisanetwork.kaisaportal.domain.dao.IAbstractDao;

public abstract class AbstractDaoImpl<T> implements IAbstractDao<T> {
	
	protected EntityManager entityManager;
	
	JpaTemplate jpaTemplate;
	
	public AbstractDaoImpl(EntityManagerFactory entityManagerFactory) {
		this.entityManager = entityManagerFactory.createEntityManager();
		jpaTemplate = new JpaTemplate(this.entityManager);
	}
	
	@SuppressWarnings("unchecked")
	public List<T> findByQuery(String str) {
		return jpaTemplate.find(str);
	}

	@SuppressWarnings("unchecked")
	public List<T> findByQuery(String str, Object values) {
		return jpaTemplate.find(str, values);
	}

	@SuppressWarnings("unchecked")
	public T findObjectForPK(Class<?> cls, Object id) {
		return (T) jpaTemplate.find(cls, id);
	}
	
	@Transactional
	public void saveObject(T entity) {
		T newEntity = entityManager.merge(entity);
		entityManager.persist(newEntity);
	}
	
	@Transactional
	public void updateObject(T entity) {
		jpaTemplate.refresh(entity);
	}

	@Transactional
	public void deleteObject(T entity) {
		jpaTemplate.remove(entity);
	}

}
